package com.kstech.exccheck.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.kstech.exccheck.R;
import com.kstech.exccheck.domain.checkline.CheckLineLoadTask;
import com.kstech.exccheck.listener.NetWorkStatusListener;
import com.kstech.exccheck.util.AppContext;
import com.kstech.exccheck.receiver.ConnStatusReceiver;
import com.kstech.exccheck.util.SystemUtil;
import com.kstech.exccheck.view.check.OpenCheckRecordActivity;
import com.kstech.exccheck.view.upload.DataUploadActivity;
import com.kstech.exccheck.view.upload.FileManagerActivity;
import com.kstech.exccheck.view.user.CurrentUserActivity;
import com.kstech.exccheck.view.user.ModPwdActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 测试 git 是否同步完成
 *
 * @author wanghaibin
 * @created 2016 -9-27 ����3:39:12
 * @since v1.0
 */
public class BaseActivity extends Activity implements NetWorkStatusListener{

	// 子标题
	private TextView subTitle;
	public TextView checkLineNameTV, userManagerRowUpTV,dataBaseRowUpTV;
	// 菜单按钮
	private ImageView indexMenuId;

	private ImageView netWorkStatus;
	// 菜单中的行
	private TableRow dataUploadRowId, userManagerRowId, modPwdRowId,
			setCheckLineRowId, exitSystemRowId, fileDownLoadRowId,dataBaseRowID;

	//private ConnStatusReceiver connStatusReceiver = new ConnStatusReceiver();

	/**
	 * 初始化菜单
	 *
	 * @param subTitleName 子菜单名称
	 */
	public void initMenu(String subTitleName) {
		subTitle = (TextView) findViewById(R.id.subTitle);

		checkLineNameTV = (TextView) findViewById(R.id.checkLineNameTV);

		// 初始化菜单组件
		LayoutInflater layoutInflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View layout = layoutInflater.inflate(
				R.layout.activity_admin_index_menu, null);
		final PopupWindow changeStatusPopUp = new PopupWindow(this);
		changeStatusPopUp.setContentView(layout);
		changeStatusPopUp.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
		changeStatusPopUp.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
		changeStatusPopUp.setFocusable(true);
		netWorkStatus = (ImageView) findViewById(R.id.connStatusId);
		//connStatusReceiver.initConnStatusImageView(this);

		// 初始化菜单按钮
		indexMenuId = (ImageView) findViewById(R.id.indexMenuId);
		indexMenuId.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				int yHeight = -160;
				if (AppContext.getCurrentUser().getType().getCode().equals("1")) {
					yHeight = -247;
				}
				changeStatusPopUp.showAtLocation(layout, Gravity.RIGHT, 0,
						yHeight);
			}
		});

		// 初始化菜单组件下的用户管理
		userManagerRowId = (TableRow) layout
				.findViewById(R.id.userManagerRowId);
		dataBaseRowID = (TableRow) layout
				.findViewById(R.id.DataBaseRowId);
		// 如果是检测员，则隐藏用户管理模块
		if (AppContext.getCurrentUser().getType().getCode().equals("1")) {
			userManagerRowId.setVisibility(View.GONE);
			userManagerRowUpTV = (TextView) layout
					.findViewById(R.id.userManagerRowUpTV);
			userManagerRowUpTV.setVisibility(View.GONE);

			dataBaseRowID.setVisibility(View.GONE);
			dataBaseRowUpTV = (TextView) layout
					.findViewById(R.id.DataBaseRowUpTV);
			dataBaseRowUpTV.setVisibility(View.GONE);

		} else {
			userManagerRowId.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(AppContext.context,
							CurrentUserActivity.class);
					startActivity(intent);
					changeStatusPopUp.dismiss();
				}
			});
			dataBaseRowID.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					changeStatusPopUp.dismiss();
					DBInject();
				}
			});
		}

		fileDownLoadRowId = (TableRow) layout.findViewById(R.id.fileDownLoadRowId);
		fileDownLoadRowId.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(AppContext.context,
						FileManagerActivity.class);
				startActivity(intent);
				changeStatusPopUp.dismiss();
			}
		});

		// 初始化菜单组件下的数据上传
		dataUploadRowId = (TableRow) layout.findViewById(R.id.dataUploadRowId);
		dataUploadRowId.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(AppContext.context,
						DataUploadActivity.class);
				startActivity(intent);
				changeStatusPopUp.dismiss();
			}
		});

		// 初始化菜单组件下的修改密码
		modPwdRowId = (TableRow) layout.findViewById(R.id.modPwdRowId);
		modPwdRowId.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(AppContext.context,
						ModPwdActivity.class);
				startActivity(intent);
				changeStatusPopUp.dismiss();
			}
		});

		// 初始化菜单组件下的检线设置
		setCheckLineRowId = (TableRow) layout
				.findViewById(R.id.setCheckLineRowId);
		setCheckLineRowId.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				changeStatusPopUp.dismiss();
				// 获取检线
				CheckLineLoadTask loadTask = new CheckLineLoadTask(
						checkLineNameTV);
				loadTask.execute(100);
			}
		});
		// 初始化菜单组件下的退出系统按钮
		exitSystemRowId = (TableRow) layout.findViewById(R.id.exitSystemRowId);
		exitSystemRowId.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				new AlertDialog.Builder(AppContext.context)
						.setTitle(R.string.diaLogWakeup)
						.setMessage(R.string.exitSystemConfirm)
						.setNegativeButton(R.string.str_close, null)
						.setPositiveButton(R.string.str_ok,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
														int which) {
										AppContext.exitSystem();
									}
								}).show();
			}
		});

		subTitle.setText(subTitleName);
		checkLineNameTV.setText(AppContext.getCurrentCheckLine().getName());
	}

	/**
	 * 数据库导入
	 */
	private void DBInject() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(AppContext.context);
		AlertDialog salert = null;
		View view = View.inflate(getApplicationContext(), R.layout.dblist_ll, null);
		File file = new File("/storage/sdcard1/DB");
		ListView lv = (ListView) view.findViewById(R.id.lv_db);
		TextView tv = (TextView)view.findViewById(R.id.tv_data_num);
		final List<String> values = new ArrayList<>();
		if(file.exists()){
            File[] files = file.listFiles();
            for (File f:files) {
                if(f.getName().matches("\\w+.db")){
                    values.add(f.getName());
                }
            }
            if(values.size()==0){
                tv.setText("DB文件夹下未找到数据库文件");
            }else {
                tv.setText("共扫描到"+values.size()+"个数据库");
            }
            lv.setAdapter(new BaseAdapter() {
                @Override
                public int getCount() {
                    return values.size();
                }

                @Override
                public Object getItem(int position) {
                    return values.get(position);
                }

                @Override
                public long getItemId(int position) {
                    return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    if(convertView==null){
                        convertView = View.inflate(AppContext.context,R.layout.ll_data_item,null);
                    }
                    TextView tv = (TextView) convertView.findViewById(R.id.dbfile);
                    tv.setText(values.get(position));
                    return convertView;
                }
            });
            salert = dialog.setView(view).create();
            final AlertDialog finalSalert = salert;
            salert.setCanceledOnTouchOutside(true);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    finalSalert.dismiss();
					final String name = values.get(position);
                    new AlertDialog.Builder(AppContext.context)
                            .setTitle("确定？")
                            .setMessage("确定要把数据库"+name+"导入吗？")
                            .setNegativeButton("取消",null)
                            .setPositiveButton("导入", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
									boolean suc = SystemUtil.copyDB(name);
									if(suc){
										Toast.makeText(AppContext.context,"数据库成功导入",Toast.LENGTH_SHORT).show();
										startActivityForResult(new Intent(AppContext.context,OpenCheckRecordActivity.class),1);
									}else {
										Toast.makeText(AppContext.context,"导入失败，请重试",Toast.LENGTH_SHORT).show();
									}
                                }
                            })
                            .show();
                }
            });
            salert.show();
        }else {
            Toast.makeText(AppContext.context,"备份数据库不存在，备份数据库应存放在\"SD卡/DB\"中--",Toast.LENGTH_SHORT).show();
        }
	}

	private ConnStatusReceiver receiver;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppContext.addActivity(this);
		// 设置上下文，保证当前页面弹窗可以正常使用
		AppContext.context = this;

		//注册广播接收器
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 设置菜单上下文
		AppContext.context = this;
		// 设置检线名称
		if (null != checkLineNameTV) {
			checkLineNameTV.setText(AppContext.getCurrentCheckLine() == null ? "未连接"
					: AppContext.getCurrentCheckLine().getName());
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}

	@Override
	public void onStatusChanged(final boolean off) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if(off){
					Log.e("off","refresh UI");
					netWorkStatus.setBackground(AppContext.context.getDrawable(R.drawable.link_no));
				}else {
					netWorkStatus.setBackground(AppContext.context.getDrawable(R.drawable.link));
				}
			}
		});

	}
}
